<?php

namespace App\Http\Controllers\Frontend\V10\UnionLogin;

use App\Constant\SmsTemplate;
use App\Library\String\Strings;
use App\Library\String\UnionLoginTools;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PiggyBankController extends Controller
{
//    const LOAD_URL = "https://manage.longloan.cn/#/fish";
    const LOAD_URL = "https://manage.longloan.cn/#/download";
    
    /**
     * 撞库返回code
     */
    const HIT_CODE_FAILURE = 0;//调用失败（接口失败、参数错误、验签错误等）
    const HIT_CODE_SUCCESS_NEW = 1; //新用户
    const HIT_CODE_SUCCESS_OLD = 2;//洋钱罐借款老用户
    const HIT_CODE_SUCCESS_OTHER_OLD = 3;//其他渠道老用户
    const HIT_CODE_BLACK_NAME = 4;//黑名单

    /**
     * 连登返回code
     */
    const UINON_CODE_FAILURE = 0;//调用接口失败（接口不可用、参数错误、验签错误等）
    const UINON_CODE_SUCCESS = 1; //联合登录成功（返回url）
    const UINON_CODE_FAILURE_LOGIN = 2;//联合登录失败（合作方返回的错误）
    const UINON_CODE_SUCCESS_OTHER_OLD = 3;//已注册用户重复注册（返回url）
/*
  0表示接口不能正常调用或者参数错误、验签错误等一些错误，用户不能正常进入接口；
2表示用户进入接口后返回的错误，如用户短时间多次调用接口等（合作方没有2类错误的话，不返回2）；
所有的“已注册用户”统一返回3，不用进行区分。
*/
   public function test_hit() {
       //撞库测试
       $md5_phone = md5(13866297830);
       var_dump($md5_phone);
       $data = [
           'channelName' => '41004',
           'mobileNumber' => $md5_phone,
           'timestamp' => '1552552440'
       ];

       $sign = UnionLoginTools::piggyBankSign($data);
//       $sign = "1DpgPvWan+kefUbTHplrSpZtByIb4LZrIjZGBBRUXI1kbEgot/VImjQSkppVLREeY4oO/F40A9rNdr7qsxbR5yYtxYfW/vX6O3y3RdKtwUDf4QMpRtp00WwNl3tBhBI5PQtpGKThnR7RjfQwQSkRbAWQ/2rGQk4FQABf1xK4jY=";
       var_dump($sign);
       $ret = UnionLoginTools::verifyPiggyBank($data,$sign);
       var_dump($ret);
   }

    public function test_register() {
        //注册测试
        $data = [
            'channelName' => '41004',
            'mobileNumber' => '13866297830',
            'timestamp' => '1552552440',
            'platformType' => 'IOS'
        ];

        $sign = UnionLoginTools::piggyBankSign($data);
//       $sign = "1DpgPvWan+kefUbTHplrSpZtByIb4LZrIjZGBBRUXI1kbEgot/VImjQSkppVLREeY4oO/F40A9rNdr7qsxbR5yYtxYfW/vX6O3y3RdKtwUDf4QMpRtp00WwNl3tBhBI5PQtpGKThnR7RjfQwQSkRbAWQ/2rGQk4FQABf1xK4jY=";
        var_dump($sign);
        $ret = UnionLoginTools::verifyPiggyBank($data,$sign);
        var_dump($ret);
    }

    /**
     * @describle 洋钱罐 验证是否撞库
     * @param Request $request
     * @return string
     * @author liChunLong
     * @date 2019-03-13 21:00
     */
   public function check(Request $request) {
      /*
       channelName	是	String	渠道名
        mobileNumber	是	String	加密后手机号
        timestamp	是	Long	时间戳（精确到毫秒）
        sign	否	String	如选择ip白名单模式对接则不需要
       */
      try{
          $paramsMap['channelName'] = $request->input('channelName', '');
          $paramsMap['mobileNumber'] = $request->input('mobileNumber', '');
          $paramsMap['timestamp'] = $request->input('timestamp', '');
          $paramsMap['sign'] = $request->input('sign', '');
          $missParams = '';
          foreach($paramsMap as $key=>$value){
              if(!$request->filled($key)){
                  $missParams = $value;
                  break;
              }
          }
          if($missParams){
              $code = self::HIT_CODE_FAILURE;
              $message = '请求参数'.$missParams.'为空';
              return json_encode(['code'=>$code,'message'=>$message],JSON_UNESCAPED_UNICODE);
          }
          $verify_data = [
              'channelName' => $paramsMap['channelName'],
              'mobileNumber' => $paramsMap['mobileNumber'],
              'timestamp' => $paramsMap['timestamp'],
          ];
          $has_pass = UnionLoginTools::verifyPiggyBank($verify_data,$paramsMap['sign']);
          if(!$has_pass){
              $code = self::HIT_CODE_FAILURE;
              $message = '数据签名错误';
              return json_encode(['code'=>$code,'message'=>$message],JSON_UNESCAPED_UNICODE);
          }

          $userModel = new User();
          $userModel->setConnection('backend');
          $has_register = $userModel->where(['phone_num_md5'=>$paramsMap['mobileNumber']])->value('id');
          if($has_register) {
              $code = self::HIT_CODE_SUCCESS_OLD;
              $message = '洋钱罐借款老用户';
              return json_encode(['code'=>$code,'message'=>$message],JSON_UNESCAPED_UNICODE);
          }
          $code = self::HIT_CODE_SUCCESS_NEW;
          $message = '新用户';
          return json_encode(['code'=>$code,'message'=>$message],JSON_UNESCAPED_UNICODE);
      }catch (\Exception $e) {
          $code = self::HIT_CODE_FAILURE;
          return json_encode(['code'=>$code,'message'=>$e->getMessage()],JSON_UNESCAPED_UNICODE);
      }
   }
    /**
     * @describle 洋钱罐 注册新用户
     * @param Request $request
     * @return string
     * @author liChunLong
     * @date 2019-03-13 21:00
     */
   public function register(Request $request)
   {
       /**
       channelName	是	String	渠道名
       mobileNumber	是	String	明文手机号
       platformType	是	String	平台类型，ANDROID / IOS / WEB / WAP / NONE
       timestamp	是	Long	时间戳（精确到毫秒）
       sign	否	String	如选择ip白名单模式对接则不需要
        */

       /*
message	String	备注信息，错误信息等
url	String	联合登录成功后的跳转链接
       */
       $url = self::LOAD_URL.'?channel='.User::SOURCE_YANG_QIAN_GUAN;
       $message = '';
       try{
           $paramsMap['channelName'] = $request->input('channelName', '');
           $paramsMap['mobileNumber'] = $request->input('mobileNumber', '');
           $paramsMap['timestamp'] = $request->input('timestamp', '');
           $paramsMap['platformType'] = $request->input('platformType', '');
           $paramsMap['sign'] = $request->input('sign', '');
           $missParams = '';
           foreach($paramsMap as $key=>$value){
               if(!$request->filled($key)){
                   $missParams = $value;
                   break;
               }
           }
           if($missParams){
               $code = self::UINON_CODE_FAILURE;
               $message = '请求参数'.$missParams.'为空';
               return json_encode(['code'=>$code,'message'=>$message,'url'=>$url],JSON_UNESCAPED_UNICODE);
           }
           $verify_data = [
               'channelName' => $paramsMap['channelName'],
               'mobileNumber' => $paramsMap['mobileNumber'],
               'timestamp' => $paramsMap['timestamp'],
               'platformType' => $paramsMap['platformType'],
           ];
           $has_pass = UnionLoginTools::verifyPiggyBank($verify_data,$paramsMap['sign']);
           if(!$has_pass){
               $code = self::UINON_CODE_FAILURE;
               $message = '数据签名错误';
               return json_encode(['code'=>$code,'message'=>$message,'url'=>$url],JSON_UNESCAPED_UNICODE);
           }
           if(User::where('phone_num',$paramsMap['mobileNumber'])->value('id')){
               $code = self::UINON_CODE_SUCCESS_OTHER_OLD;
               $message = '已注册用户重复注册';
               return json_encode(['code'=>$code,'message'=>$message,'url'=>$url],JSON_UNESCAPED_UNICODE);
           }
           $rand_code =Strings::randomCode(6);
           User::createUser([
               'phone_num' => $paramsMap['mobileNumber'],
               'password' => $rand_code,
               'source' => User::SOURCE_YANG_QIAN_GUAN,
           ]);
           $send_mobile = $paramsMap['mobileNumber'];
           //推送用户，快闪卡贷自动注册成功
           SmsTemplate::send(SmsTemplate::TEMPLATE_RZG_REGISTER,$send_mobile,['name'=>$send_mobile,'password'=>$rand_code]);
           $code = self::UINON_CODE_SUCCESS;
           $message = '成功';
           return json_encode(['code'=>$code,'message'=>$message,'url'=>$url],JSON_UNESCAPED_UNICODE);
       }catch (\Exception $e) {
           $code = self::UINON_CODE_FAILURE;
           $message = $e->getMessage();
           return json_encode(['code'=>$code,'message'=>$message,'url'=>$url],JSON_UNESCAPED_UNICODE);
       }
   }
}
